//
//  YDYSeeBigPicViewController.m
//  DYSisterAPP
//
//  Created by 杨德勇 on 2016/8/8.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

#import "YDYSeeBigPicViewController.h"
#import "YDYTopic.h"
#import <UIImageView+WebCache.h>
#import <Photos/Photos.h>
#import <SVProgressHUD.h>

#pragma mark -
#pragma mark -常量定义
//相册名字
static NSString* YDYAssetCollectionTitle = @"德勇百思";
#pragma mark -
@interface YDYSeeBigPicViewController ()<UIScrollViewDelegate>
/** 图片 */
@property (nonatomic, weak) UIImageView *imgView;

@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

@end

@implementation YDYSeeBigPicViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    //顶掉原来的view
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.delegate = self;
    scrollView.frame = [UIScreen mainScreen].bounds;
    [self.view insertSubview:scrollView atIndex:0];
    //设置图片
    UIImageView *imgview = [[UIImageView alloc]init];
    [imgview sd_setImageWithURL:[NSURL URLWithString:self.topic.large_img] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image == nil) return;
        self.saveBtn.enabled = YES;
    }];
    
    [scrollView addSubview:imgview];
    //设置imgview的frame
    imgview.ydy_height = self.topic.height * scrollView.ydy_width / self.topic.width;
    imgview.ydy_width = scrollView.ydy_width;
    imgview.ydy_x = 0;
    
    if (imgview.ydy_height > scrollView.ydy_height){
        imgview.ydy_y = 0;
        scrollView.contentSize = CGSizeMake(0, imgview.ydy_height);
    }else{
        //图片不够一个屏幕大
        imgview.ydy_centerY = scrollView.ydy_height * 0.5;
        
    }
    //保存imgview
    self.imgView = imgview;
    
    //修改放大比例
    CGFloat scale = self.topic.width / imgview.ydy_width;
    if (scale > 1) {
        [scrollView setMaximumZoomScale:scale];
    }
}


- (IBAction)saveBtnClick:(id)sender {
    //判断用户是否授权保存照片
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    switch (status) {
        case PHAuthorizationStatusRestricted:
            [SVProgressHUD showErrorWithStatus:@"系统原因，无法访问照片"];
            break;
        case PHAuthorizationStatusDenied:
            [SVProgressHUD showErrorWithStatus:@"请到设置中允许APP访问照片"];
            
            break;
        case PHAuthorizationStatusNotDetermined:
            //让用户选择授权
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {}];
            break;
        case PHAuthorizationStatusAuthorized:
            //用户允许
            [self saveImage];
            break;
    }
}

-(void)saveImage{

    //图片唯一标示
    __block NSString *assetIdentifier = nil;
    
    //保存图片的操作是在子线程上面执行，所有相关的都要写在代码块里面
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        //1.保存图片到“胶卷”中
        assetIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.imgView.image].placeholderForCreatedAsset.localIdentifier;
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        //保存不成功，直接返回
        if (!success) {[SVProgressHUD showErrorWithStatus:@"无法保存到胶卷"];return;}
        //2.拿到相簿
        PHAssetCollection *collection = [self getAssetCollecton];
        //3.把图片存在相册当中
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            
            //获取图片 asset
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetIdentifier] options:nil].lastObject;
            
            //把图片放进去
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
            [request addAssets:@[asset]];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success){
                //保存成功
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            }else{
                //保存失败
                [SVProgressHUD showErrorWithStatus:@"无法保存到相簿中"];
                return;
            }
            
        }];
        
    }];
    
    
    
    
}

-(PHAssetCollection *)getAssetCollecton{
    //1.先检查以前有没有这个相簿
    //获取所有的相簿
    PHFetchResult<PHAssetCollection *> * collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    //获取自己的相簿
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:YDYAssetCollectionTitle]) {
            return collection;
        }
    }
    
    //2.创建新的相簿
    __block NSString *collectionIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        //创新相簿，拿到identifier
        collectionIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:YDYAssetCollectionTitle].placeholderForCreatedAssetCollection.localIdentifier;
        
    } error:nil];
    //返回拿到的相簿
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionIdentifier] options:nil].lastObject;
    
}
- (IBAction)backBtnClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark -
#pragma mark -scrollviewdelegate
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imgView;
}
@end
